package com.example.springboottestgit.controller.main;

import com.alibaba.fastjson.JSONObject;
import com.example.springboottestgit.bean.vo.InputVO;
import com.example.springboottestgit.utils.ExcelExportUtil;
import com.example.springboottestgit.utils.HttpUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @description:
 * @author: ZZZ
 */
public class AirQualityTest {
    public static void main(String[] args) {
        //A();//连续
        //B();//随机
        C();//单气体连续


    }

    public static void A() {
        //
        List<AirQuality> list = readExcelList("C:\\Users\\user\\Desktop\\北京空气质量0304\\验证集A-连续.xlsx");

        List<String> keys = new ArrayList<>();
        for (int i = 0; i < list.size() - 6; i = i + 4) {
            Random random = new Random();
            //int n = random.nextInt(list.size() - 6);
            int n = i;
            String instruction = "请根据提供的过去5天空气质量情况，帮我预测下一天的空气质量情况。\n";
            String input = getStr(list.get(n)) + "\n" + getStr(list.get(n + 1)) + "\n" + getStr(list.get(n + 2)) + "\n" + getStr(list.get(n + 3)) + "\n" + getStr(list.get(n + 4));
            String question = instruction + input;
            InputVO inputVO = new InputVO();
            inputVO.setQuestion(question);
            String params = JSONObject.toJSONString(inputVO);
            System.out.println(question);
            String result = HttpUtils.post("http://192.168.80.102:21048/infer", params);
            System.out.println(result);
            String newAqi = "xxx";
            String newLevel = "xxx";
            String[] pms = result.split("PM");

            if (pms[0].contains("质量等级")) {

                String[] zldj = pms[0].split("质量等级");


                zldj[1] = zldj[1].replace("\"", "").replace("为", "").replace("。", "")
                        .replace(":", "")
                        .replace("：", "")
                        .replace("（", "")
                        .replace("）", "")
                        .replace("(", "")
                        .replace(")", "")
                        .replace(",", "")
                        .replace("，", "");

                if (zldj[1].contains("AQI")) {
                    String[] split = zldj[1].split("AQI");

                    //newLevel = split[0].substring(5);
                    newLevel = split[0].replace(" ", "").replace("质量等级", "").replace("：", "");
                    //newAqi = split[1].substring(6);
                    newAqi = split[1].replace(" ", "").replace("AQI指数", "").replace("：", "")
                            .replace("指数", "")
                            .replace("值", "");
                    System.out.println(newLevel);
                    System.out.println(newAqi);
                    String level = list.get(n + 5).getLevel();
                    String aqi = list.get(n + 5).getAqi();
                    String regex = "^[-+]?\\d+$";

                    // 创建Pattern对象
                    Pattern pattern = Pattern.compile(regex);
                    // 创建Matcher对象，并尝试匹配字符串
                    Matcher matcher = pattern.matcher(newAqi);
                    if (matcher.matches()) {
                        list.get(n + 5).setAqiDifference(String.valueOf(Math.abs(Integer.valueOf(aqi) - Integer.valueOf(newAqi))));
                    }

                    list.get(n + 5).setLevelCompare(level.equals(newLevel));

                    list.get(n + 5).setMark("ok");
                }


            }

            System.out.println();


            list.get(n + 5).setResult(result);
            list.get(n + 5).setNewAqi(newAqi);
            list.get(n + 5).setNewLevel(newLevel);


        }
        export(list, "C:\\Users\\user\\Desktop\\北京空气质量0304\\测试\\验证集A-连续-测试.xlsx");

    }

    public static void B() {
        List<AirQuality> list = readExcelList("C:\\Users\\user\\Desktop\\北京空气质量0305\\验证集B-随机.xlsx");
        List<AirQuality> list1 = readExcelList("C:\\Users\\user\\Desktop\\北京空气质量0305\\验证集A-连续.xlsx");
        list.addAll(list1);

        for (AirQuality airQuality : list) {
            String level = airQuality.getLevel();
            String AQI = airQuality.getAqi();
            String PM2 = airQuality.getPm2();
            String PM10 = airQuality.getPm10();
            String SO2 = airQuality.getSo2();
            String NO2 = airQuality.getNo2();
            String CO = airQuality.getCo();
            String O3 = airQuality.getO3();
            String instruction = "请根据我提供的空气质量中污染物浓度的含量，帮我预测空气的质量等级和AQI指数。\n";
            String input = String.format("PM2.5 : %s, PM10 : %s, So2 : %s, No2 : %s, Co : %s, O3 : %s", PM2, PM10, SO2, NO2, CO, O3);

            String question = instruction + input;
            InputVO inputVO = new InputVO();
            inputVO.setQuestion(question);
            String params = JSONObject.toJSONString(inputVO);
            System.out.println(question);

            String result = HttpUtils.post("http://192.168.80.102:21048/infer", params);
            System.out.println(result);
            System.out.println();

            String newAqi = "xxx";
            String newLevel = "xxx";
            String[] pms = result.split("PM");

            if (pms[0].contains("质量等级")) {

                String[] zldj = pms[0].split("质量等级");

                zldj[1] = zldj[1].replace("\"", "").replace("为", "").replace("。", "")
                        .replace(":", "")
                        .replace("：", "")
                        .replace("（", "")
                        .replace("）", "")
                        .replace("(", "")
                        .replace(")", "")
                        .replace(",", "")
                        .replace("，", "");

                if (zldj[1].contains("AQI")) {
                    String[] split = zldj[1].split("AQI");

                    //newLevel = split[0].substring(5);
                    newLevel = split[0].replace(" ", "").replace("质量等级", "").replace("：", "");
                    //newAqi = split[1].substring(6);
                    newAqi = split[1].replace(" ", "").replace("AQI指数", "").replace("：", "")
                            .replace("指数", "")
                            .replace("值", "");
                    System.out.println(newLevel);
                    System.out.println(newAqi);

                    String regex = "^[-+]?\\d+$";

                    // 创建Pattern对象
                    Pattern pattern = Pattern.compile(regex);
                    // 创建Matcher对象，并尝试匹配字符串
                    Matcher matcher = pattern.matcher(newAqi);
                    if (matcher.matches()) {
                        airQuality.setAqiDifference(String.valueOf(Math.abs(Integer.valueOf(AQI) - Integer.valueOf(newAqi))));
                    }

                    airQuality.setLevelCompare(level.equals(newLevel));

                    airQuality.setMark("ok");
                }
            }
            airQuality.setResult(result);
            airQuality.setNewAqi(newAqi);
            airQuality.setNewLevel(newLevel);
        }
        export(list, "C:\\Users\\user\\Desktop\\北京空气质量0305\\测试\\验证集AB-测试.xlsx");

    }

    public static void C() {

        List<AirQuality> list = readExcelList("C:\\Users\\user\\Desktop\\北京空气质量0305\\验证集A-连续.xlsx");
        List<AirQuality> newList = new ArrayList<>();
        for (int i = 0; i < list.size() - 6; i = i + 3) {
            //Random random = new Random();
            //int n = random.nextInt(list.size() - 6);
            String pm2 = "";
            String pm10 = "";
            String so2 = "";
            String no2 = "";
            String co = "";
            String o3 = "";

            for (int j = i; j < 5 + i; j++) {
                newList.add(list.get(j));
                pm2 = pm2 + "PM2.5 : " + list.get(j).getPm2() + ";\n";
                pm10 = pm10 + "PM10 : " + list.get(j).getPm10() + ";\n";
                so2 = so2 + "So2 : " + list.get(j).getSo2() + ";\n";
                no2 = no2 + "No2 : " + list.get(j).getNo2() + ";\n";
                co = co + "Co : " + list.get(j).getCo() + ";\n";
                o3 = o3 + "O3 : " + list.get(j).getO3() + ";\n";
            }


            AirQuality quality = new AirQuality();
            quality.setPm2(generateInstructData("请根据提供的过去5天空气中PM2.5污染物的浓度数据，帮我预测下一天的空气中PM2.5污染物的浓度数据。\n", pm2));
            quality.setPm10(generateInstructData("请根据提供的过去5天空气中PM10污染物的浓度数据，帮我预测下一天的空气中PM10污染物的浓度数据。\n", pm10));
            quality.setSo2(generateInstructData("请根据提供的过去5天空气中So2污染物的浓度数据，帮我预测下一天的空气中So2污染物的浓度数据。\n", so2));
            quality.setNo2(generateInstructData("请根据提供的过去5天空气中No2污染物的浓度数据，帮我预测下一天的空气中No2污染物的浓度数据。\n", no2));
            quality.setCo(generateInstructData("请根据提供的过去5天空气中Co污染物的浓度数据，帮我预测下一天的空气中Co污染物的浓度数据。\n", co));
            quality.setO3(generateInstructData("请根据提供的过去5天空气中O3污染物的浓度数据，帮我预测下一天的空气中O3污染物的浓度数据。\n", o3));
            list.get(i + 5).setMark("实际值");
            newList.add(list.get(i + 5));
            String level = list.get(i + 5).getLevel();
            String AQI = list.get(i + 5).getAqi();

            String PM2 = quality.getPm2();
            String PM10 = quality.getPm10();
            String SO2 = quality.getSo2();
            String NO2 = quality.getNo2();
            String CO = quality.getCo();
            String O3 = quality.getO3();
            String instruction = "请根据我提供的空气质量中污染物浓度的含量，帮我预测空气的质量等级和AQI指数。\n";
            String input = String.format("PM2.5 : %s, PM10 : %s, So2 : %s, No2 : %s, Co : %s, O3 : %s", PM2, PM10, SO2, NO2, CO, O3);

            String question = instruction + input;
            InputVO inputVO = new InputVO();
            inputVO.setQuestion(question);
            String params = JSONObject.toJSONString(inputVO);
            System.out.println(question);
            String result = HttpUtils.post("http://192.168.80.102:21048/infer", params);
            System.out.println(result);
            String newAqi = "xxx";
            String newLevel = "xxx";
            String[] pms = result.split("PM");

            if (pms[0].contains("质量等级")) {

                String[] zldj = pms[0].split("质量等级");

                zldj[1] = zldj[1].replace("\"", "").replace("为", "").replace("。", "")
                        .replace(":", "")
                        .replace("：", "")
                        .replace("（", "")
                        .replace("）", "")
                        .replace("(", "")
                        .replace(")", "")
                        .replace(",", "")
                        .replace("，", "");

                if (zldj[1].contains("AQI")) {
                    String[] split = zldj[1].split("AQI");

                    //newLevel = split[0].substring(5);
                    newLevel = split[0].replace(" ", "").replace("质量等级", "").replace("：", "");
                    //newAqi = split[1].substring(6);
                    newAqi = split[1].replace(" ", "").replace("AQI指数", "").replace("：", "")
                            .replace("指数", "")
                            .replace("值", "");
                    System.out.println(newLevel);
                    System.out.println(newAqi);

                    String regex = "^[-+]?\\d+$";

                    // 创建Pattern对象
                    Pattern pattern = Pattern.compile(regex);
                    // 创建Matcher对象，并尝试匹配字符串
                    Matcher matcher = pattern.matcher(newAqi);
                    if (matcher.matches()) {
                        quality.setAqiDifference(String.valueOf(Math.abs(Integer.valueOf(AQI) - Integer.valueOf(newAqi))));
                    }

                    quality.setLevelCompare(level.equals(newLevel));

                    quality.setMark("测试值");
                }
            }
            quality.setResult(result);
            quality.setNewAqi(newAqi);
            quality.setAqi(newAqi);
            quality.setNewLevel(newLevel);
            quality.setLevel(newLevel);
            newList.add(quality);

            export(newList, "C:\\Users\\user\\Desktop\\北京空气质量0305\\测试\\验证集A-单气体连续-测试.xlsx");

        }

    }

    public static String generateInstructData(String instruction, String input) {
        InputVO inputVO = new InputVO();
        inputVO.setQuestion(instruction + input);
        String params = JSONObject.toJSONString(inputVO);
        System.out.println(inputVO.getQuestion());
        String result = HttpUtils.post("http://192.168.80.102:21048/infer", params);
        System.out.println(result);
        String newResult=result.split(":")[1].replace(" ","").replace("\"","");
        System.out.println(newResult);
        return newResult;
    }


    public static List<AirQuality> readExcelList(String excelFilePath) {
        List<AirQuality> list = new ArrayList<>();
        try (FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
             Workbook workbook = new XSSFWorkbook(inputStream)) {
            Sheet sheet = workbook.getSheetAt(0); // 读取第一个工作表
            for (Row row : sheet) { // 迭代每一行
                //System.out.print(row.getCell(0) + "\t");
                //System.out.println(row.getCell(1));
                //System.out.println(row.getCell(1));

                if ("日期".equals(String.valueOf(row.getCell(0)))) {
                    continue;
                }

                String date = String.valueOf(row.getCell(0));
                String level = String.valueOf(row.getCell(1));
                String AQI = String.valueOf(row.getCell(2));
                String PM2 = String.valueOf(row.getCell(3));
                String PM10 = String.valueOf(row.getCell(4));
                String SO2 = String.valueOf(row.getCell(5));
                String NO2 = String.valueOf(row.getCell(6));
                String CO = String.valueOf(row.getCell(7));
                String O3 = String.valueOf(row.getCell(8));

                AirQuality air = new AirQuality();
                air.setDate(date);
                air.setLevel(level);
                air.setAqi(AQI);
                air.setPm2(PM2);
                air.setPm10(PM10);
                air.setSo2(SO2);
                air.setNo2(NO2);
                air.setCo(CO);
                air.setO3(O3);
                list.add(air);

//                for (Cell cell : row) { // 迭代每一列
//                    // 根据不同数据类型，以字符串形式输出数据
//                    System.out.print(cell.getStringCellValue() + "\t");
//
//                }
//                System.out.println(); // 换行
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static void export(List<AirQuality> result, String outputFilePath) {

        List<Map<String, Object>> list = JSONObject.parseObject(JSONObject.toJSONString(result), List.class);
        //表头数组 日期	质量等级	AQI指数	当天AQI排名	PM2.5	PM10	So2	No2	Co	O3
        String[] lables = new String[]{"日期", "质量等级", "AQI指数", "PM2.5", "PM10", "So2", "No2", "Co", "O3", "结果", "质量等级", "AQI", "质量等级对比", "AQI差值", "标记"};
        //查询数据对应的属性数组

        String[] fields = new String[]{"date", "level", "aqi", "pm2", "pm10", "so2", "no2", "co", "o3", "result", "newLevel", "newAqi", "levelCompare", "aqiDifference", "mark"};
        String title = "空气质量数据.xlsx";
        String headTitle = "指令集";
        //if (result.size() > 1) {
        //title = result.get(0).getName() + "(" + result.get(0).getCode() + ")" + "历史数据.xlsx";
        //headTitle = result.get(0).getName() + "(" + result.get(0).getCode() + ")" + "历史数据";
        //}
        ExcelExportUtil.export(outputFilePath, list, lables, fields, title);

    }

    public static String getStr(AirQuality airQuality) {
        String level = airQuality.getLevel();
        String AQI = airQuality.getAqi();
        String PM2 = airQuality.getPm2();
        String PM10 = airQuality.getPm10();
        String SO2 = airQuality.getSo2();
        String NO2 = airQuality.getNo2();
        String CO = airQuality.getCo();
        String O3 = airQuality.getO3();
        String str = String.format("质量等级：%s，AQI指数：%s,PM2.5 : %s, PM10 : %s, So2 : %s, No2 : %s, Co : %s, O3 : %s;", level, AQI, PM2, PM10, SO2, NO2, CO, O3);
        return str;

    }
}
